#include "server_wight.h"
#include "ui_server_wight.h"

Server_wight::Server_wight(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::Server_wight)
{
    ui->setupUi(this);

    //Label UI
    Host=new QLabel(this);
    Port=new QLabel(this);
    info_type=new QLabel(this);
    rec_IP=new QLabel(this);
    rec_Port=new QLabel(this);
    post_IP=new QLabel(this);
    post_Port=new QLabel(this);
    url_ip=new QLabel(this);
    url_port=new QLabel(this);

    Host->setText("Host IP");
    Port->setText("Host Port");
    info_type->setText("task_type");
    rec_IP->setText("onboard_rec_IP");
    rec_Port->setText("onboard_rec_Port");
    post_IP->setText("onboard_post_IP");
    post_Port->setText("onboard_post_Port");
    url_ip->setText("task_url_ip");
    url_port->setText("task_url_port");

    Host->move(10,10);
    Port->move(150,10);

    info_type->move(10,50);
    rec_IP->move(10,90);
    rec_Port->move(150,90);
    post_IP->move(10,130);
    post_Port->move(150,130);
    url_ip->move(10,170);
    url_port->move(150,170);

    //LineEdit UI
    insert_IP=new QLineEdit(this);
    insert_Port=new QLineEdit(this);
    insert_tpye=new QLineEdit(this);
    insert_rec_IP=new QLineEdit(this);
    insert_rec_port=new QLineEdit(this);
    insert_post_IP=new QLineEdit(this);
    insert_post_port=new QLineEdit(this);
    in_url_ip=new QLineEdit(this);
    in_url_port=new QLineEdit(this);

    insert_tpye->setText("object_tracking");
    insert_rec_IP->setText("192.168.1.50");
    insert_rec_port->setText("8554");

    insert_IP->setText("192.168.1.132");
    insert_Port->setText("8888");
    insert_post_IP->setText("192.168.1.132");
    insert_post_port->setText("8888");
    in_url_ip->setText("192.168.1.50");
    in_url_port->setText("1234");

    insert_IP->move(10,35);
    insert_Port->move(150,35);
    insert_tpye->move(10,75);
    insert_rec_IP->move(10,115);
    insert_rec_port->move(150,115);
    insert_post_IP->move(10,155);
    insert_post_port->move(150,155);
    in_url_ip->move(10,195);
    in_url_port->move(150,195);

    rce_show=new QTextEdit(this);
    rce_show->move(10,230);
    rce_show->setFixedSize(100,80);
    rce_show->setText("wait recvice info....");
    //PushButton UI
    send_info=new QPushButton(this);
    send_info->setText("send");
    send_info->move(150,230);
    connect(send_info,SIGNAL(clicked()),this,SLOT(send_info_ser()));
    connect(insert_IP,SIGNAL(textChanged(QString)),this,SLOT(slot_textChange_ip(QString)));
    connect(insert_Port,SIGNAL(textChanged(QString)),this,SLOT(slot_textChange_port(QString)));



}

Server_wight::~Server_wight()
{
    delete ui;
}

void Server_wight::send_info_ser()
{
    widget=new QWidget(this);
    layout=new QVBoxLayout(widget);
    imageLabel=new QLabel(widget);
    layout->addWidget(imageLabel);
    widget->setWindowTitle("this is image window");
    widget->setWindowFlag(Qt::Window);
    // 创建网络访问管理器
    QNetworkAccessManager *manager = new QNetworkAccessManager;
    // 设置请求URL
    QString url_address="http://"+in_url_ip->text()+":"+in_url_port->text()+"/task";

    QUrl url(url_address);

    // 创建请求对象
    QNetworkRequest request;
    request.setUrl(url);

    // 设置请求头
    request.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));

    // create JSON object
    QJsonObject json;
    QString post_address="http://"+insert_post_IP->text()+":"+insert_post_port->text();
    QString recv_address="rtsp://"+insert_rec_IP->text()+":"+insert_rec_port->text()+"/test";
    json["task_type"] = "object_tracking";
    QJsonArray post_array;
    post_array.push_back(post_address);
    QJsonArray recv_array;
    recv_array.push_back(recv_address);
    json["onboard_post_data_address"] = post_array;
    json["onboard_receive_data_address"] = recv_array;


    // 将JSON对象转换为字节数组
    QJsonDocument doc(json);
    QByteArray data = doc.toJson();


    // 发送POST请求
    manager->post(request, data.data());
    // 处理响应
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onReplyFinished(QNetworkReply*)));
}

void Server_wight::onReplyFinished(QNetworkReply* reply)
{
    if (reply->error() == QNetworkReply::NoError) {
        qDebug() << "POST request successful!";
        QByteArray responseData = reply->readAll();
        rce_show->setText(responseData);
        QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObject = jsonResponse.object();
        if(jsonObject["code"].toString()=="Success")
        {

            host_server=new QTcpServer(this);
            cli_date=nullptr;
            QString date_ip=insert_IP->text();
            quint16 date_port=insert_Port->text().toInt();
            host_server->listen(QHostAddress(date_ip),date_port);
            connect(host_server,&QTcpServer::newConnection,this,&Server_wight::recv_connect);

        }
        qDebug() << "Response data:" << responseData;
    } else {
        qDebug() << "Error:" << reply->errorString();
    }
}

void Server_wight::slot_textChange_ip(QString text)
{
    insert_post_IP->setText(text);

}

void Server_wight::slot_textChange_port(QString text)
{
    insert_post_port->setText(text);
}

void Server_wight::recv_connect()
{
//    qDebug() <<"2222222";
    cli_date=host_server->nextPendingConnection();
    connect(cli_date,&QTcpSocket::readyRead,this,&Server_wight::read_date);

}

void Server_wight::read_date()
{
//    qDebug() <<"11111111";
    QByteArray imageData = cli_date->readAll(); // 读取二进制数据
    QByteArray imageDataWithoutHeader = imageData.mid(imageData.indexOf("\xFF\xD8")); // 删除 JPEG 文件头之前的数据
    QByteArray jpegData = imageDataWithoutHeader.mid(0, imageDataWithoutHeader.lastIndexOf("\xFF\xD9") + 2); // 提取 JPEG 文件
//    qDebug() <<image_date.data();
    widget->show();
    QImage image;
    if (image.loadFromData(jpegData)) {
        qDebug() << "Image loaded successfully!";
        // 在GUI中显示图像
        imageLabel->setPixmap(QPixmap::fromImage(image));
    }
    else {
        qDebug() << "Failed to load image!";
    }
cli_date->write("Received");
cli_date->waitForBytesWritten();
cli_date->close();

}


